# -*- coding: utf-8 -*-
import logging
import os
import sys
import time
from datetime import datetime, timedelta

import requests
from bs4 import BeautifulSoup

# add up one level dir into sys path
from common.lottery.handler import crawl_from_opencai

sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(
    os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "base.settings")

from common.lottery.cyclical.cq_ssc.db.activity import fullfill_result
from common.lottery import LOTTERY_TYPE, PROXY_URL, OPENCAI_LOTTERY_TYPES
from common.timer import TIMER_EVENT_TYPE, TimerEvent
from common.utils import tz


def _get_default_date():
    date = tz.utc_to_local(datetime.utcnow())
    # 如果是第二天刚开始的时候，需要去爬前一天最后几期的结果
    if date.hour == 0 and date.minute < 3:
        date -= timedelta(days=1)
    return date


def crawl_from_168(date=None):
    calc_date = date or _get_default_date()
    url = 'http://api.1680210.com/CQShiCai/getBaseCQShiCaiList.do?lotCode=10002&date=%s' % calc_date.strftime(
        '%Y-%m-%d')
    try:
        response = requests.get(url, proxies={'http': PROXY_URL}, timeout=10)
    except Exception as e:
        raise e
    if response.status_code != 200:
        raise RuntimeError('request error')
    _parse_and_fill_168(response.json(), url)


def _parse_and_fill_168(data, refer):
    if data['errorCode'] == 0:
        nodes = data['result']['data']
        for node in nodes:
            phase = node['preDrawIssue']
            number = node['preDrawCode'].replace(',', '')
            activity = fullfill_result(phase, number, refer)
            if activity:
                TimerEvent.submit(TIMER_EVENT_TYPE.CALC_STATS, {
                    'number': number, 'term': phase,
                    'activity_type': LOTTERY_TYPE.CQ_SSC}, tz.now_ts()
                                  )
                TimerEvent.submit(TIMER_EVENT_TYPE.ACTIVITY_ANNOUNCE, {
                    'number': number, 'term': phase,
                    'activity_type': LOTTERY_TYPE.CQ_SSC}, tz.now_ts())


def crawl_from_baidu(date=None):
    calc_date = date or _get_default_date()
    headers = {
        'Pragma': 'no-cache',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'Referer': 'http://www.lecai.com/lottery/draw/sorts/cqssc.php',
        'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',
        'Accept-Encoding': 'gzip, deflate, sdch',
    }
    url = 'http://www.lecai.com/lottery/draw/sorts/ajax_get_draw_data.php?lottery_type=200&date='
    reference = 'http://www.lecai.com/lottery/draw/sorts/cqssc.php'
    response = requests.get(url + calc_date.strftime('%Y-%m-%d'), headers=headers, proxies={'http': PROXY_URL},
                            timeout=1)
    data = response.json()['data']['data']
    # 为了处理漏期问题，总是解析全部
    for s in data:
        phase = s['phase']
        number = ''.join(s['result']['result'][0]['data'])
        refer = reference + '?date=' + calc_date.strftime('%Y%m%d')
        activity = fullfill_result(phase, number, refer)
        if activity:
            TimerEvent.submit(TIMER_EVENT_TYPE.CALC_STATS, {
                'number': number, 'term': phase,
                'activity_type': LOTTERY_TYPE.CQ_SSC}, tz.now_ts())
            TimerEvent.submit(TIMER_EVENT_TYPE.ACTIVITY_ANNOUNCE, {
                'number': number, 'term': phase,
                'activity_type': LOTTERY_TYPE.CQ_SSC}, tz.now_ts())
            time.sleep(1)


def crawl_from_163(date=None):
    calc_date = date or _get_default_date()
    date_str = calc_date.strftime('%Y%m%d')
    url = 'http://caipiao.163.com/award/daily_refresh.html?gameEn=ssc&date=' + date_str
    _HEADERS = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json',
    }
    response = requests.get(url, headers=_HEADERS, proxies={'http': PROXY_URL}, timeout=30)
    soup = BeautifulSoup(response.content, "lxml")
    tds = soup.find_all('td', {'class': 'start'})
    for td in tds:
        if td.get('data-win-number'):
            phase = date_str + td.get_text()
            number = td.get('data-win-number').replace(' ', '')
            refer = url
            activity = fullfill_result(phase, number, refer)
            if activity:
                TimerEvent.submit(TIMER_EVENT_TYPE.CALC_STATS, {
                    'number': number, 'term': phase,
                    'activity_type': LOTTERY_TYPE.CQ_SSC}, tz.now_ts())
                TimerEvent.submit(TIMER_EVENT_TYPE.ACTIVITY_ANNOUNCE, {
                    'number': number, 'term': phase,
                    'activity_type': LOTTERY_TYPE.CQ_SSC}, tz.now_ts())
                time.sleep(1)


def main(d):
    while True:
        try:
            crawl_from_opencai(LOTTERY_TYPE.CQ_SSC)
        except Exception as e:
            logging.exception(u'%s error: %s' % (OPENCAI_LOTTERY_TYPES.get(LOTTERY_TYPE.CQ_SSC), e))
        if d:
            break
        time.sleep(60)


if __name__ == '__main__':
    date = sys.argv[1] if len(sys.argv) > 1 else None
    main(date)
